import posixpath
from collections.abc import Generator

import oss2 as aliyun_s3  # type: ignore

from configs import app_config
from extensions.storage.base_storage import BaseStorage
# import logging

class AliyunOssStorage(BaseStorage):
    """Implementation for Aliyun OSS storage."""

    def __init__(self):
        super().__init__()
        self.bucket_name = app_config.ALIYUN_OSS_BUCKET_NAME
        self.folder = app_config.ALIYUN_OSS_PATH
        self.my_domain = app_config.ALIYUN_OSS_DOMAIN
        self.end_point = app_config.ALIYUN_OSS_ENDPOINT
        oss_auth_method = aliyun_s3.Auth
        region = None
        if app_config.ALIYUN_OSS_AUTH_VERSION == "v4":
            oss_auth_method = aliyun_s3.AuthV4
            region = app_config.ALIYUN_OSS_REGION
        oss_auth = oss_auth_method(app_config.ALIYUN_OSS_ACCESS_KEY, app_config.ALIYUN_OSS_SECRET_KEY)
        self.client = aliyun_s3.Bucket(
            oss_auth,
            app_config.ALIYUN_OSS_ENDPOINT,
            self.bucket_name,
            connect_timeout=30,
            region=region,
        )

    def save(self, filename, data):
        self.client.put_object(self.__wrapper_folder_filename(filename), data)

    def load_once(self, filename: str) -> bytes:
        obj = self.client.get_object(self.__wrapper_folder_filename(filename))
        data: bytes = obj.read()
        return data

    def load_stream(self, filename: str) -> Generator:
        obj = self.client.get_object(self.__wrapper_folder_filename(filename))
        while chunk := obj.read(4096):
            yield chunk

    def download(self, filename: str, target_filepath):
        self.client.get_object_to_file(self.__wrapper_folder_filename(filename), target_filepath)

    def exists(self, filename: str):
        return self.client.object_exists(self.__wrapper_folder_filename(filename))

    def delete(self, filename: str):
        self.client.delete_object(self.__wrapper_folder_filename(filename))

    def __wrapper_folder_filename(self, filename: str) -> str:
        return posixpath.join(self.folder, filename) if self.folder else filename
    
    def sign_url(
            self, file_id: str, file_path: str, expiration_time: int
        ):
            # headers = {"Content-Disposition": "inline"}
            if self.folder:
                file_path = self.folder+'/'+file_path
            params = {
                # 'response-content-type': 'image/jpeg',  # 根据你的文件类型调整MIME类型
                "response-content-disposition": "inline"  # 强制浏览器尝试在窗口内打开文件
            }

            # headers = aliyun_s3.CaseInsensitiveDict({"Content-Disposition": "inline"})
            url = self.client.sign_url(
                "GET", file_path, expiration_time, params=params, slash_safe=True
            )
            if self.my_domain:
                url2 = url.replace(f"{self.bucket_name}.{self.end_point}", self.my_domain)
                url = url2.replace(f"http", 'https')
                # logging.info(f"sign url:{url}\nurl2:{url2}")
            return url
